package netty.im;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.util.Scanner;

public class IMClient {


    public static void main(String[] args) throws InterruptedException {
        Channel[] channels = new Channel[1];
        new Thread(() -> {
            try {
                Bootstrap b = new Bootstrap()
                        .group(new NioEventLoopGroup())
                        .channel(NioSocketChannel.class)
                        .option(ChannelOption.TCP_NODELAY, true)
                        .handler(new ClientHandler());
                ChannelFuture f = b.connect("localhost", 8080).sync();
                System.out.println("客户端启动..");
                channels[0] = f.channel();
                System.out.println("client通道:" + channels[0].toString());
                f.channel().closeFuture().sync();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
        while (true) {
            Scanner scanner = new Scanner(System.in);
            String sc = scanner.nextLine();
            String line = channels[0].id() + ":" + sc + "\n";
            System.out.println("控制台输入:" + line);
            channels[0].writeAndFlush(line);
        }
    }
}
